<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"lishx.com","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"hide","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="SpringMVC的基本概念关于三层架构和MVC三层架构 开发服务器端的程序，一般都是基于两种形式，分别叫做B&#x2F;S即浏览器服务器，和C&#x2F;S即客户端服务器。 使用Java语言基本上都是开发B&#x2F;S架构的程序，B&#x2F;S架构又分成了三层架构 三层架构： 表现层：WEB层，用来和客户端进行交互的，表现层一般会使用MVC的设计模型 业务层：处理公司具体的业务逻辑 持久层：用来操作数据库">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC">
<meta property="og:url" content="lishx.com/2020/09/02/java/springmvc/index.html">
<meta property="og:site_name" content="lishouxian&#39;s BLOG">
<meta property="og:description" content="SpringMVC的基本概念关于三层架构和MVC三层架构 开发服务器端的程序，一般都是基于两种形式，分别叫做B&#x2F;S即浏览器服务器，和C&#x2F;S即客户端服务器。 使用Java语言基本上都是开发B&#x2F;S架构的程序，B&#x2F;S架构又分成了三层架构 三层架构： 表现层：WEB层，用来和客户端进行交互的，表现层一般会使用MVC的设计模型 业务层：处理公司具体的业务逻辑 持久层：用来操作数据库">
<meta property="og:locale">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gic400ei2uj31dp0u0dku.jpg">
<meta property="og:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gic4p6e2yhj32480u04mh.jpg">
<meta property="article:published_time" content="2020-09-02T11:00:00.000Z">
<meta property="article:modified_time" content="2020-09-05T08:53:21.717Z">
<meta property="article:author" content="李寿贤">
<meta property="article:tag" content="javaweb框架">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://tva1.sinaimg.cn/large/007S8ZIlly1gic400ei2uj31dp0u0dku.jpg">

<link rel="canonical" href="lishx.com/2020/09/02/java/springmvc/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>SpringMVC | lishouxian's BLOG</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">lishouxian's BLOG</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="lishx.com/2020/09/02/java/springmvc/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="李寿贤">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="lishouxian's BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          SpringMVC
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-09-02 19:00:00" itemprop="dateCreated datePublished" datetime="2020-09-02T19:00:00+08:00">2020-09-02</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-09-05 16:53:21" itemprop="dateModified" datetime="2020-09-05T16:53:21+08:00">2020-09-05</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javaweb/" itemprop="url" rel="index"><span itemprop="name">javaweb</span></a>
                </span>
            </span>

          
            <span id="/2020/09/02/java/springmvc/" class="post-meta-item leancloud_visitors" data-flag-title="SpringMVC" title="Views">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">Views: </span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine: </span>
    
    <a title="valine" href="/2020/09/02/java/springmvc/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/09/02/java/springmvc/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="SpringMVC的基本概念"><a href="#SpringMVC的基本概念" class="headerlink" title="SpringMVC的基本概念"></a>SpringMVC的基本概念</h2><h3 id="关于三层架构和MVC"><a href="#关于三层架构和MVC" class="headerlink" title="关于三层架构和MVC"></a>关于三层架构和MVC</h3><h4 id="三层架构"><a href="#三层架构" class="headerlink" title="三层架构"></a>三层架构</h4><ul>
<li>开发服务器端的程序，一般都是基于两种形式，分别叫做B/S即浏览器服务器，和C/S即客户端服务器。</li>
<li>使用Java语言基本上都是开发B/S架构的程序，B/S架构又分成了三层架构</li>
<li>三层架构：<ul>
<li>表现层：WEB层，用来和客户端进行交互的，表现层一般会使用MVC的设计模型</li>
<li>业务层：处理公司具体的业务逻辑</li>
<li>持久层：用来操作数据库</li>
</ul>
</li>
</ul>
<a id="more"></a>

<h4 id="MVC模型"><a href="#MVC模型" class="headerlink" title="MVC模型"></a>MVC模型</h4><ul>
<li>MVC全名是Model View Controller模型视图控制器，每个部分各司其职。</li>
<li>Model：数据模型，Java Bean的类，用来进行数据封装</li>
<li>View： 指JSP、HTML等用来展示数据给用户</li>
<li>Controller： 用来接受用户的请求，整个流程的控制器。用来进行数据校验等。</li>
</ul>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gic400ei2uj31dp0u0dku.jpg" alt="三层架构"></p>
<h2 id="SpringMVC的入门案例"><a href="#SpringMVC的入门案例" class="headerlink" title="SpringMVC的入门案例"></a>SpringMVC的入门案例</h2><h3 id="SpringMVC的概述"><a href="#SpringMVC的概述" class="headerlink" title="SpringMVC的概述"></a>SpringMVC的概述</h3><ul>
<li>SpringMVC的概述：<ul>
<li>是一种基于Java程序实现的MVC设计模型的请求驱动类型的轻量级WEB框架</li>
<li>属于SpringFrameworks的后续产品，现在已经融合在Spring Web Flow里面。提供了构建Web应用程序的全功能MVC模块</li>
<li>使用Sprint可插入MVC架构从而使使用Spring进行WEB开发时，可以选择使用Spring的SpringMVC框架或者集成其他MVC框架</li>
</ul>
</li>
<li>SpringMVC框架在三层架构中的位置：表现层框架</li>
<li>SpringMVC框架的优势</li>
</ul>
<h3 id="SpringMVC的入门程序"><a href="#SpringMVC的入门程序" class="headerlink" title="SpringMVC的入门程序"></a>SpringMVC的入门程序</h3><h4 id="创建WEB工程，引入JAR包"><a href="#创建WEB工程，引入JAR包" class="headerlink" title="创建WEB工程，引入JAR包"></a>创建WEB工程，引入JAR包</h4><p>Pom.xml具体的坐标如下图所示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">  </span><br><span class="line"><span class="comment">&lt;!-- 版本锁定 --&gt;</span> <span class="tag">&lt;<span class="name">properties</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">spring.version</span>&gt;</span>5.0.2.RELEASE<span class="tag">&lt;/<span class="name">spring.version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">properties</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependencies</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-context<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;spring.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-web<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;spring.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-webmvc<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>$&#123;spring.version&#125;<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>servlet-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.5<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>javax.servlet.jsp<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jsp-api<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">scope</span>&gt;</span>provided<span class="tag">&lt;/<span class="name">scope</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependencies</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="配置核心的控制器-配置DispatcherServlet"><a href="#配置核心的控制器-配置DispatcherServlet" class="headerlink" title="配置核心的控制器(配置DispatcherServlet)"></a>配置核心的控制器(配置DispatcherServlet)</h4><p> 在web.xml配置文件中核心控制器DispatcherServlet</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- SpringMVC的核心控制器 --&gt;</span> <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>dispatcherServlet<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-</span></span></span><br><span class="line"><span class="tag"><span class="attr">class</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置Servlet的初始化参数，读取springmvc的配置文件，创建spring容器 --&gt;</span> <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>classpath:springmvc.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置servlet启动时加载对象 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>dispatcherServlet<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">  </span><br></pre></td></tr></table></figure>

<p>编写springmvc.xml的配置文件</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line"><span class="meta">&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">beans</span> <span class="attr">xmlns</span>=<span class="string">&quot;http://www.springframework.org/schema/beans&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:mvc</span>=<span class="string">&quot;http://www.springframework.org/schema/mvc&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:context</span>=<span class="string">&quot;http://www.springframework.org/schema/context&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xmlns:xsi</span>=<span class="string">&quot;http://www.w3.org/2001/XMLSchema-instance&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">xsi:schemaLocation</span>=<span class="string">&quot;</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/beans/spring-beans.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/mvc</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/mvc/spring-mvc.xsd</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context</span></span></span><br><span class="line"><span class="tag"><span class="string">        http://www.springframework.org/schema/context/spring-context.xsd&quot;</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置spring创建容器时要扫描的包 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">context:component-scan</span> <span class="attr">base-package</span>=<span class="string">&quot;com.itheima&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">context:component-scan</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置视图解析器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;viewResolver&quot;</span></span></span><br><span class="line"><span class="tag"><span class="attr">class</span>=<span class="string">&quot;org.springframework.web.servlet.view.InternalResourceViewResolver&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;prefix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;/WEB-INF/pages/&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;suffix&quot;</span> <span class="attr">value</span>=<span class="string">&quot;.jsp&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 配置spring开启注解mvc的支持</span></span><br><span class="line"><span class="comment">    &lt;mvc:annotation-driven&gt;&lt;/mvc:annotation-driven&gt;--&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">beans</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>编写index.jsp</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line">&lt;body&gt;</span><br><span class="line">&lt;h3&gt;入门案例&lt;/h3&gt;</span><br><span class="line">&lt;a href=&quot;$&#123; pageContext.request.contextPath &#125;/hello&quot;&gt;入门案例&lt;/a&gt;</span><br><span class="line">&lt;/body&gt;</span><br></pre></td></tr></table></figure>

<p>HelloController控制器类</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">package</span> cn.itcast.controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Controller;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.RequestMapping;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 控制器</span></span><br><span class="line"><span class="comment">* <span class="doctag">@author</span> rt */</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloController</span> </span>&#123;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 接收请求 * <span class="doctag">@return</span> */</span></span><br><span class="line">    <span class="meta">@RequestMapping(path=&quot;/hello&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;Hello SpringMVC!!&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在WEB-INF目录下创建pages文件夹，编写success.jsp的成功页面</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;body&gt;</span><br><span class="line">     &lt;h3&gt;入门成功!!&lt;/h3&gt;</span><br><span class="line">&lt;/body&gt;</span><br></pre></td></tr></table></figure>

<h4 id="入门案例的执行过程分析"><a href="#入门案例的执行过程分析" class="headerlink" title="入门案例的执行过程分析"></a>入门案例的执行过程分析</h4><ol>
<li><p>入门案例的执行流程</p>
<ol>
<li>当启动tomcat服务器的时候因为配置了load-on-start标签，所以会创建dispatchServlet对象，就会加载Springmvc.xml配置文件</li>
<li>开启了注解扫描，那么hello controller就会被创建</li>
<li>从index.jsp发送请求，请求会首先到达DispatchServlet核心控制器，再根据配置@PequestMapping注解找到执行的具体方法</li>
<li>根据执行方法的返回值，再根据配置试图解析器，去指定的目录下寻找jsp文件</li>
<li>Tomcat服务器响应</li>
</ol>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlly1gic4p6e2yhj32480u04mh.jpg" alt="MVC执行过程"></p>
</li>
<li><p>入门案例中的组件分析</p>
<ol>
<li>前端控制器(DispatcherServlet) </li>
<li>处理器映射器(HandlerMapping) </li>
<li>处理器(Handler)</li>
<li>处理器适配器(HandlAdapter)</li>
<li>视图解析器(View Resolver)</li>
<li>视图(View)</li>
</ol>
</li>
<li><p>RequestMapping注解</p>
<ol>
<li>RequestMapping注解的作用是建立请求URL和处理方法之间的对应关系</li>
<li>RequestMapping注解可以作用在方法和类上<ol>
<li>作用在类上:第一级的访问目录</li>
<li>作用在方法上:第二级的访问目录</li>
<li>细节:路径可以不编写 / 表示应用的根目录开始</li>
<li>细节:${ pageContext.request.contextPath }也可以省略不写，但是路径上不能写 /</li>
</ol>
</li>
<li>RequestMapping的属性<ol>
<li>path ： 默认</li>
<li>value</li>
<li>mthod</li>
<li>params</li>
<li>headers 发送的请求中必须包含的请求头</li>
</ol>
</li>
</ol>
</li>
</ol>
<h2 id="请求参数的绑定"><a href="#请求参数的绑定" class="headerlink" title="请求参数的绑定"></a>请求参数的绑定</h2><h3 id="请求参数的绑定说明"><a href="#请求参数的绑定说明" class="headerlink" title="请求参数的绑定说明"></a>请求参数的绑定说明</h3><ul>
<li><p>绑定机制</p>
<ul>
<li>表单提交的数据都是k-v格式的 username=xiaomei&amp;password=123</li>
<li>Spring MVC的参数绑定过程及欧式把表单提交的请求参数，作为控制器中的方法的参数来进行绑定</li>
<li>要求是：提交表单的name和参数的名称是一样的</li>
</ul>
</li>
<li><p>支持的数据类型</p>
<ul>
<li>基本数据类型和字符串类型</li>
<li>实体类型：那么与属性名称一致，假如包含其他引用类型，则写成对象.属性的方式：address.name</li>
<li>集合数据类型（List、Map集合等） JSP页面编写方式:list[0].属性</li>
<li>基本数据类型和字符串数据类型区分大小写</li>
</ul>
</li>
<li><p>解决中文乱码的问题</p>
<ul>
<li>在web.xml中配置Spring提供的过滤器类</li>
</ul>
</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置过滤器，解决中文乱码的问题 --&gt;</span> <span class="tag">&lt;<span class="name">filter</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>characterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-class</span>&gt;</span>org.springframework.web.filter.CharacterEncodingFilter<span class="tag">&lt;/<span class="name">filter-</span></span></span><br><span class="line"><span class="tag"><span class="attr">class</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 指定字符集 --&gt;</span> <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>encoding<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>UTF-8<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">filter-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">filter-name</span>&gt;</span>characterEncodingFilter<span class="tag">&lt;/<span class="name">filter-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">filter-mapping</span>&gt;</span></span><br></pre></td></tr></table></figure>

<ul>
<li>自定义类型转换器<ul>
<li>表单中提交的任何数据类型全部都是字符串类型，但是 后台定义的Integer类型也能封装上，说明Spring框架内会进行默认的数据类型转换</li>
<li>如果想要自定义数据类型转化，可以实现Converter的接口<ul>
<li>自定义类型转换器</li>
</ul>
</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> cn.itcast.utils;</span><br><span class="line"><span class="keyword">import</span> java.text.DateFormat;</span><br><span class="line"><span class="keyword">import</span> java.text.SimpleDateFormat;</span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.convert.converter.Converter;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 把字符串转换成日期的转换器 * <span class="doctag">@author</span> rt</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringToDateConverter</span> <span class="keyword">implements</span> <span class="title">Converter</span>&lt;<span class="title">String</span>, <span class="title">Date</span>&gt;</span>&#123;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 进行类型转换的方法 */</span></span><br><span class="line">	<span class="function"><span class="keyword">public</span> Date <span class="title">convert</span><span class="params">(String source)</span> </span>&#123; <span class="comment">// 判断</span></span><br><span class="line">		<span class="keyword">if</span>(source == <span class="keyword">null</span>) &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;参数不能为空&quot;</span>);</span><br><span class="line">	&#125;</span><br><span class="line">    	<span class="keyword">try</span> &#123;</span><br><span class="line">			DateFormat df = <span class="keyword">new</span> SimpleDateFormat(<span class="string">&quot;yyyy-MM-dd&quot;</span>); <span class="comment">// 解析字符串</span></span><br><span class="line">			Date date = df.parse(source);</span><br><span class="line">			<span class="keyword">return</span> date;</span><br><span class="line">		&#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">			<span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;类型转换错误&quot;</span>);</span><br><span class="line">		&#125;&#125;</span><br><span class="line">&#125;</span><br><span class="line">  </span><br></pre></td></tr></table></figure>

<p>注册自定义类型转换器，在springmvc.xml配置文件中编写配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line"><span class="comment">&lt;!-- 注册自定义类型转换器 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;conversionService&quot;</span></span></span><br><span class="line"><span class="tag"><span class="attr">class</span>=<span class="string">&quot;org.springframework.context.support.ConversionServiceFactoryBean&quot;</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;converters&quot;</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">set</span>&gt;</span></span><br><span class="line">                <span class="tag">&lt;<span class="name">bean</span> <span class="attr">class</span>=<span class="string">&quot;cn.itcast.utils.StringToDateConverter&quot;</span>/&gt;</span></span><br><span class="line">            <span class="tag">&lt;/<span class="name">set</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!-- 开启Spring对MVC注解的支持 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:annotation-driven</span> <span class="attr">conversion-service</span>=<span class="string">&quot;conversionService&quot;</span>/&gt;</span></span><br></pre></td></tr></table></figure>

<p>在控制器中使用原生的ServletAPI对象：只需要在控制器的方法参数定义HttpServletRequest和HttpServletResponse对象</p>
<h2 id="常用的注解"><a href="#常用的注解" class="headerlink" title="常用的注解"></a>常用的注解</h2><h3 id="RequestParam注解"><a href="#RequestParam注解" class="headerlink" title="@RequestParam注解"></a>@RequestParam注解</h3><ul>
<li><p>作用：把请求中的指定名称的参数传递给控制器中的形参赋值</p>
</li>
<li><p>属性：</p>
<ul>
<li>value：请求参数中的名称</li>
<li>required：请求参数中是否必须提供此参数，默认值是true，必须提供</li>
</ul>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">* 接收请求 * <span class="doctag">@return</span> */</span></span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/hello&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(<span class="meta">@RequestParam(value=&quot;username&quot;,required=false)</span>String name)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;aaaa&quot;</span>);</span><br><span class="line">    System.out.println(name);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="RequestBody注解"><a href="#RequestBody注解" class="headerlink" title="@RequestBody注解"></a>@RequestBody注解</h3><ul>
<li><p>作用:用于获取请求体的内容(注意:get方法不可以)</p>
</li>
<li><p>属性</p>
</li>
<li><p>required:是否必须有请求体，默认值是true</p>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">* 接收请求 * <span class="doctag">@return</span> */</span></span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/hello&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(<span class="meta">@RequestBody</span> String body)</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;aaaa&quot;</span>);</span><br><span class="line">    System.out.println(body);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="PathVariable注解"><a href="#PathVariable注解" class="headerlink" title="@PathVariable注解"></a>@PathVariable注解</h3><ul>
<li><p>作用:拥有绑定url中的占位符的。例如:url中有/delete/{id}，{id}就是占位符 </p>
</li>
<li><p>属性</p>
</li>
<li><p>value:指定url中的占位符名称</p>
</li>
<li><p>Restful风格的URL</p>
<ul>
<li>请求路径一样，可以根据不同的请求方式去执行后台的不同方法 </li>
<li>restful风格的URL优点<ul>
<li>结构清晰 </li>
<li>符合标准</li>
<li>易于理解</li>
<li>扩展方便</li>
</ul>
</li>
</ul>
</li>
<li><p>代码如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"> &lt;a href=&quot;user/hello/1&quot;&gt;入门案例&lt;/a&gt;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 接收请求 * <span class="doctag">@return</span> */</span></span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/hello/&#123;id&#125;&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(<span class="meta">@PathVariable(value=&quot;id&quot;)</span> String id)</span> </span>&#123;</span><br><span class="line">    System.out.println(id);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<h3 id="RequestHeader注解"><a href="#RequestHeader注解" class="headerlink" title="@RequestHeader注解"></a>@RequestHeader注解</h3><ul>
<li><p>作用：获取请求头的值</p>
</li>
<li><p>属性</p>
<ul>
<li>value：请求头的名称</li>
</ul>
</li>
<li><p>代码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(path=&quot;/hello&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(<span class="meta">@RequestHeader(value=&quot;Accept&quot;)</span> String header)</span> </span>&#123;</span><br><span class="line">       System.out.println(header);</span><br><span class="line">       <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="CookieValue注解"><a href="#CookieValue注解" class="headerlink" title="CookieValue注解"></a>CookieValue注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@RequestMapping(path=&quot;/hello&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">(<span class="meta">@CookieValue(value=&quot;JSESSIONID&quot;)</span> String cookieValue)</span> </span>&#123;</span><br><span class="line">    System.out.println(cookieValue);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ModelAttribute注解"><a href="#ModelAttribute注解" class="headerlink" title="ModelAttribute注解"></a>ModelAttribute注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ModelAttribute</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> User <span class="title">showUser</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">	System.out.println(<span class="string">&quot;showUser执行了...&quot;</span>); <span class="comment">// 模拟从数据库中查询对象</span></span><br><span class="line">	User user = <span class="keyword">new</span> User(); user.setName(<span class="string">&quot;哈哈&quot;</span>);</span><br><span class="line">    user.setPassword(<span class="string">&quot;123&quot;</span>); user.setMoney(<span class="number">100d</span>);</span><br><span class="line">    <span class="keyword">return</span> user;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/updateUser&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">updateUser</span><span class="params">(User user)</span> </span>&#123;</span><br><span class="line">    System.out.println(user);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ModelAttribute</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">showUser</span><span class="params">(String name,Map&lt;String, User&gt; map)</span> </span>&#123;</span><br><span class="line">System.out.println(<span class="string">&quot;showUser执行了...&quot;</span>); <span class="comment">// 模拟从数据库中查询对象</span></span><br><span class="line">User user = <span class="keyword">new</span> User(); user.setName(<span class="string">&quot;哈哈&quot;</span>); user.setPassword(<span class="string">&quot;123&quot;</span>); user.setMoney(<span class="number">100d</span>);</span><br><span class="line">    map.put(<span class="string">&quot;abc&quot;</span>, user);</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/updateUser&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">updateUser</span><span class="params">(<span class="meta">@ModelAttribute(value=&quot;abc&quot;)</span> User user)</span> </span>&#123;</span><br><span class="line">    System.out.println(user);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="SessionAttributes注解"><a href="#SessionAttributes注解" class="headerlink" title="SessionAttributes注解"></a>SessionAttributes注解</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="meta">@RequestMapping(path=&quot;/user&quot;)</span></span><br><span class="line"><span class="meta">@SessionAttributes(value= &#123;&quot;username&quot;,&quot;password&quot;,&quot;age&quot;&#125;,types=</span></span><br><span class="line"><span class="meta">&#123;String.class,Integer.class&#125;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">HelloController</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 向session中存入值 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">    */</span></span><br><span class="line">    <span class="comment">// 把数据存入到session域对象中</span></span><br><span class="line">    <span class="meta">@RequestMapping(path=&quot;/save&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">save</span><span class="params">(Model model)</span> </span>&#123;</span><br><span class="line">    	System.out.println(<span class="string">&quot;向session域中保存数据&quot;</span>); </span><br><span class="line">        model.addAttribute(<span class="string">&quot;username&quot;</span>, <span class="string">&quot;root&quot;</span>); </span><br><span class="line">        model.addAttribute(<span class="string">&quot;password&quot;</span>, <span class="string">&quot;123&quot;</span>); </span><br><span class="line">        model.addAttribute(<span class="string">&quot;age&quot;</span>, <span class="number">20</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="meta">@RequestMapping(path=&quot;/find&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">find</span><span class="params">(ModelMap modelMap)</span> </span>&#123;</span><br><span class="line">        String username = (String) modelMap.get(<span class="string">&quot;username&quot;</span>);</span><br><span class="line">        String password = (String) modelMap.get(<span class="string">&quot;password&quot;</span>);</span><br><span class="line">        Integer age = (Integer) modelMap.get(<span class="string">&quot;age&quot;</span>);</span><br><span class="line">        System.out.println(username + <span class="string">&quot; : &quot;</span>+password +<span class="string">&quot; : &quot;</span>+age);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@RequestMapping(path=&quot;/delete&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">delete</span><span class="params">(SessionStatus status)</span> </span>&#123;</span><br><span class="line">        status.setComplete();</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="Controller响应数据和结果试图"><a href="#Controller响应数据和结果试图" class="headerlink" title="Controller响应数据和结果试图"></a>Controller响应数据和结果试图</h2><h3 id="返回值分类"><a href="#返回值分类" class="headerlink" title="返回值分类"></a>返回值分类</h3><h4 id="返回字符串"><a href="#返回字符串" class="headerlink" title="返回字符串"></a>返回字符串</h4><p>Controller方法返回字符串可以指定逻辑视图的名称，根据视图解析器为物理视图的地址</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/hello&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">sayHello</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;Hello SpringMVC!!&quot;</span>); <span class="comment">// 跳转到XX页面</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>响应的数据：使用<code>model.addAttribute(&quot;user&quot;, user)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">   <span class="meta">@RequestMapping(value=&quot;/initUpdate&quot;)</span></span><br><span class="line">   <span class="function"><span class="keyword">public</span> String <span class="title">initUpdate</span><span class="params">(Model model)</span> </span>&#123;</span><br><span class="line">       <span class="comment">// 模拟从数据库中查询的数据</span></span><br><span class="line">       User user = <span class="keyword">new</span> User(); user.setUsername(<span class="string">&quot;张三&quot;</span>); </span><br><span class="line">       user.setPassword(<span class="string">&quot;123&quot;</span>); user.setMoney(<span class="number">100d</span>); </span><br><span class="line">       user.setBirthday(<span class="keyword">new</span> Date());</span><br><span class="line">       model.addAttribute(<span class="string">&quot;user&quot;</span>, user);</span><br><span class="line">       <span class="keyword">return</span> <span class="string">&quot;update&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight jsp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;h3&gt;修改用户&lt;/h3&gt;</span><br><span class="line">$&#123; requestScope &#125;</span><br><span class="line">&lt;form action=<span class="string">&quot;user/update&quot;</span> method=<span class="string">&quot;post&quot;</span>&gt;</span><br><span class="line">    </span><br><span class="line">	姓名:&lt;input type=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;username&quot;</span> value=<span class="string">&quot;$&#123; user.username &#125;&quot;</span>&gt;</span><br><span class="line">    &lt;br&gt; 密码:&lt;input type=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;password&quot;</span> value=<span class="string">&quot;$&#123; user.password &#125;&quot;</span>&gt;</span><br><span class="line">    &lt;br&gt; 金额:&lt;input type=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;money&quot;</span> value=<span class="string">&quot;$&#123; user.money &#125;&quot;</span>&gt;</span><br><span class="line">    &lt;br&gt; &lt;input type=<span class="string">&quot;submit&quot;</span> value=<span class="string">&quot;提交&quot;</span>&gt;</span><br><span class="line">&lt;/form&gt;</span><br><span class="line">  </span><br></pre></td></tr></table></figure>

<h4 id="返回值是void"><a href="#返回值是void" class="headerlink" title="返回值是void"></a>返回值是void</h4><p>如果控制器的方法返回值编写成void，会自动跳转到方法名所在的JSP页面-@RequestMapping(value=”/initUpdate”) initUpdate的页面。</p>
<p>可以请求转发或者重定向到指定的页面</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/initAdd&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initAdd</span><span class="params">(HttpServletRequest request,HttpServletResponse response)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">    System.out.println(<span class="string">&quot;请求转发或者重定向&quot;</span>);</span><br><span class="line">    <span class="comment">// 请求转发</span></span><br><span class="line">    <span class="comment">// request.getRequestDispatcher(&quot;/WEBINF/pages/add.jsp&quot;).forward(request,response);</span></span><br><span class="line">    <span class="comment">// 重定向</span></span><br><span class="line">    <span class="comment">// response.sendRedirect(request.getContextPath()+&quot;/add2.jsp&quot;);</span></span><br><span class="line">    response.setCharacterEncoding(<span class="string">&quot;UTF-8&quot;</span>);</span><br><span class="line">    response.setContentType(<span class="string">&quot;text/html;charset=UTF-8&quot;</span>);</span><br><span class="line">	<span class="comment">// 直接响应数据 response.getWriter().print(&quot;你好&quot;); return;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>返回值是ModelAndView对象 ModelAndView对象是Spring提供的一个对象，可以用来调整具体的JSP视图</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(value=&quot;/findAll&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ModelAndView <span class="title">findAll</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">ModelAndView mv = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">    <span class="comment">// 跳转到list.jsp的页面 mv.setViewName(&quot;list&quot;);</span></span><br><span class="line"><span class="comment">// 模拟从数据库中查询所有的用户信息 List&lt;User&gt; users = new ArrayList&lt;&gt;(); User user1 = new User(); user1.setUsername(&quot;张三&quot;); user1.setPassword(&quot;123&quot;);</span></span><br><span class="line">	User user2 = <span class="keyword">new</span> User();</span><br><span class="line">    user2.setUsername(<span class="string">&quot;赵四&quot;</span>);</span><br><span class="line">    user2.setPassword(<span class="string">&quot;456&quot;</span>);</span><br><span class="line">  	users.add(user1);</span><br><span class="line">    users.add(user2);</span><br><span class="line">	<span class="comment">// 添加对象 mv.addObject(&quot;users&quot;, users);</span></span><br><span class="line">	<span class="keyword">return</span> mv;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="SpringMVC框架提供的转发和重定向"><a href="#SpringMVC框架提供的转发和重定向" class="headerlink" title="SpringMVC框架提供的转发和重定向"></a>SpringMVC框架提供的转发和重定向</h3><h4 id="forward请求转发"><a href="#forward请求转发" class="headerlink" title="forward请求转发"></a>forward请求转发</h4><p> controller方法返回String类型，想进行请求转发也可以编写成<code>return &quot;forward:/user/findAll&quot;</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 使用forward关键字进行请求转发</span></span><br><span class="line"><span class="comment">* &quot;forward:转发的JSP路径&quot;，不走视图解析器了，所以需要编写完整的路径 * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">* <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/delete&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">delete</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	System.out.println(<span class="string">&quot;delete方法执行了...&quot;</span>);</span><br><span class="line">	<span class="comment">// return &quot;forward:/WEB-INF/pages/success.jsp&quot;;</span></span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;forward:/user/findAll&quot;</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="redirect重定向"><a href="#redirect重定向" class="headerlink" title="redirect重定向"></a>redirect重定向</h4><p>controller方法返回String类型，想进行重定向也可以编写成<code>return &quot;redirect:/add.jsp&quot;</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">* 重定向</span></span><br><span class="line"><span class="comment">* <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">* <span class="doctag">@throws</span> Exception */</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/count&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> String <span class="title">count</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	System.out.println(<span class="string">&quot;count方法执行了...&quot;</span>);</span><br><span class="line">    <span class="keyword">return</span> <span class="string">&quot;redirect:/add.jsp&quot;</span>;</span><br><span class="line">	<span class="comment">// return &quot;redirect:/user/findAll&quot;;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ResponseBody响应json数据"><a href="#ResponseBody响应json数据" class="headerlink" title="ResponseBody响应json数据"></a>ResponseBody响应json数据</h3><p>DispatcherServlet会拦截到所有的资源，导致一个问题就是静态资源(img、css、js)也会被拦截到，从而</p>
<p>不能被使用。解决问题就是需要配置静态资源不进行拦截，在springmvc.xml配置文件添加如下配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 设置静态资源不过滤 --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:resources</span> <span class="attr">location</span>=<span class="string">&quot;/css/&quot;</span> <span class="attr">mapping</span>=<span class="string">&quot;/css/**&quot;</span>/&gt;</span> <span class="comment">&lt;!-- 样式 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:resources</span> <span class="attr">location</span>=<span class="string">&quot;/images/&quot;</span> <span class="attr">mapping</span>=<span class="string">&quot;/images/**&quot;</span>/&gt;</span> <span class="comment">&lt;!-- 图片 --&gt;</span> </span><br><span class="line"><span class="tag">&lt;<span class="name">mvc:resources</span> <span class="attr">location</span>=<span class="string">&quot;/js/&quot;</span> <span class="attr">mapping</span>=<span class="string">&quot;/js/**&quot;</span>/&gt;</span> <span class="comment">&lt;!-- javascript --&gt;</span></span><br></pre></td></tr></table></figure>

<p>json字符串和JavaBean对象互相转换的过程中，需要使用jackson的jar包</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-databind<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.9.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-core<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.9.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.fasterxml.jackson.core<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>jackson-annotations<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.9.0<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="使用-RequestBody获取请求体数据"><a href="#使用-RequestBody获取请求体数据" class="headerlink" title="使用@RequestBody获取请求体数据"></a>使用@RequestBody获取请求体数据</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="comment">// 绑定点击事件 $(&quot;#btn&quot;).click(function()&#123;</span></span><br><span class="line">        $.ajax(&#123;</span><br><span class="line">            url:<span class="string">&quot;user/testJson&quot;</span>,</span><br><span class="line">            contentType:<span class="string">&quot;application/json;charset=UTF-8&quot;</span>,</span><br><span class="line">            data:<span class="string">&#x27;&#123;&quot;addressName&quot;:&quot;aa&quot;,&quot;addressNum&quot;:100&#125;&#x27;</span>,</span><br><span class="line">            dataType:<span class="string">&quot;json&quot;</span>,</span><br><span class="line">            type:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">            success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">                alert(data);</span><br><span class="line">                alert(data.addressName);</span><br><span class="line">            &#125;</span><br><span class="line">&#125;); &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">* 获取请求体的数据 * <span class="meta">@param</span> body</span><br><span class="line">*/</span><br><span class="line"><span class="meta">@RequestMapping(&quot;/testJson&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testJson</span><span class="params">(<span class="meta">@RequestBody</span> String body)</span> </span>&#123;</span><br><span class="line">    System.out.println(body);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="使用-RequestBody注解把json的字符串转换成JavaBean的对象"><a href="#使用-RequestBody注解把json的字符串转换成JavaBean的对象" class="headerlink" title="使用@RequestBody注解把json的字符串转换成JavaBean的对象"></a>使用@RequestBody注解把json的字符串转换成JavaBean的对象</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="comment">// 绑定点击事件 $(&quot;#btn&quot;).click(function()&#123;</span></span><br><span class="line">        $.ajax(&#123;</span><br><span class="line">            url:<span class="string">&quot;user/testJson&quot;</span>,</span><br><span class="line">            contentType:<span class="string">&quot;application/json;charset=UTF-8&quot;</span>,</span><br><span class="line">            data:<span class="string">&#x27;&#123;&quot;addressName&quot;:&quot;aa&quot;,&quot;addressNum&quot;:100&#125;&#x27;</span>,</span><br><span class="line">            dataType:<span class="string">&quot;json&quot;</span>,</span><br><span class="line">            type:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">            success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">                alert(data);</span><br><span class="line">                alert(data.addressName);</span><br><span class="line">            &#125;</span><br><span class="line">&#125;); &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 获取请求体的数据 * <span class="doctag">@param</span> body</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="meta">@RequestMapping(&quot;/testJson&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testJson</span><span class="params">(<span class="meta">@RequestBody</span> Address address)</span> </span>&#123;</span><br><span class="line">    System.out.println(address);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="使用-ResponseBody注解把JavaBean对象转换成json字符串"><a href="#使用-ResponseBody注解把JavaBean对象转换成json字符串" class="headerlink" title="使用@ResponseBody注解把JavaBean对象转换成json字符串"></a>使用@ResponseBody注解把JavaBean对象转换成json字符串</h4><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">$(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="comment">// 绑定点击事件 $(&quot;#btn&quot;).click(function()&#123;</span></span><br><span class="line">            $.ajax(&#123;</span><br><span class="line">                url:<span class="string">&quot;user/testJson&quot;</span>,</span><br><span class="line">                contentType:<span class="string">&quot;application/json;charset=UTF-8&quot;</span>,</span><br><span class="line">				data:<span class="string">&#x27;&#123;&quot;addressName&quot;:&quot;哈哈&quot;,&quot;addressNum&quot;:100&#125;&#x27;</span>,</span><br><span class="line">                dataType:<span class="string">&quot;json&quot;</span>,</span><br><span class="line">                type:<span class="string">&quot;post&quot;</span>,</span><br><span class="line">                success:<span class="function"><span class="keyword">function</span>(<span class="params">data</span>)</span>&#123;</span><br><span class="line">                    alert(data);</span><br><span class="line">                    alert(data.addressName);</span><br><span class="line">            &#125;</span><br><span class="line">&#125;); &#125;);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequestMapping(&quot;/testJson&quot;)</span></span><br><span class="line"><span class="keyword">public</span> <span class="meta">@ResponseBody</span> <span class="function">Address <span class="title">testJson</span><span class="params">(<span class="meta">@RequestBody</span> Address address)</span> </span>&#123;</span><br><span class="line">System.out.println(address); address.setAddressName(<span class="string">&quot;上海&quot;</span>); <span class="keyword">return</span> address;</span><br><span class="line">&#125;</span><br><span class="line">  </span><br></pre></td></tr></table></figure>

<h2 id="SpringMVC实现文件上传"><a href="#SpringMVC实现文件上传" class="headerlink" title="SpringMVC实现文件上传"></a>SpringMVC实现文件上传</h2><h3 id="文件上传的回顾"><a href="#文件上传的回顾" class="headerlink" title="文件上传的回顾"></a>文件上传的回顾</h3><p><strong>导入文件上传的maven依赖</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-fileupload<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.3.1<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-io<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">      <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>添加multipartResolver的Bean配置</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- 配置multipartResolver--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">&quot;multipartResolver&quot;</span>  <span class="attr">class</span>=<span class="string">&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- 设置上传文件的最大尺寸为 50MB --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">&quot;maxUploadSize&quot;</span> <span class="attr">value</span>=<span class="string">&quot;52428800&quot;</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="编写文件上传的JSP页面"><a href="#编写文件上传的JSP页面" class="headerlink" title="编写文件上传的JSP页面"></a>编写文件上传的JSP页面</h4><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;h3&gt;测试文件上传&lt;/h3&gt;</span><br><span class="line">&lt;form action=<span class="string">&quot;fileupload&quot;</span> method=<span class="string">&quot;post&quot;</span> enctype=<span class="string">&quot;multipart/form-data&quot;</span>&gt;</span><br><span class="line">    选择文件:&lt;input type=<span class="string">&quot;file&quot;</span> name=<span class="string">&quot;file&quot;</span>/&gt;&lt;br/&gt;</span><br><span class="line">    选择描述:&lt;input type=<span class="string">&quot;text&quot;</span> name=<span class="string">&quot;desc&quot;</span>/&gt;&lt;br/&gt;</span><br><span class="line">    &lt;input type=<span class="string">&quot;submit&quot;</span> value=<span class="string">&quot;上传文件&quot;</span>/&gt;</span><br><span class="line">&lt;/form&gt;</span><br></pre></td></tr></table></figure>

<h4 id="编写文件上传的Controller控制器"><a href="#编写文件上传的Controller控制器" class="headerlink" title="编写文件上传的Controller控制器"></a>编写文件上传的Controller控制器</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 文件上传</span></span><br><span class="line"><span class="comment">* <span class="doctag">@throws</span> Exception */</span></span><br><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">UploadController</span> </span>&#123;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@RequestMapping(&quot;fileupload&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">testupload</span><span class="params">(String desc,MultipartFile file</span></span></span><br><span class="line"><span class="function"><span class="params">    )</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        System.out.println(desc);</span><br><span class="line">        System.out.println(file.getOriginalFilename());</span><br><span class="line">        System.out.println(file.getInputStream());</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="多文件上传MultipartFile-file-遍历"><a href="#多文件上传MultipartFile-file-遍历" class="headerlink" title="多文件上传MultipartFile[] file + 遍历"></a>多文件上传<code>MultipartFile[] file</code> + 遍历</h4><h2 id="SpringMVC的拦截器"><a href="#SpringMVC的拦截器" class="headerlink" title="SpringMVC的拦截器"></a>SpringMVC的拦截器</h2><p>SpringMVc提供了拦截器机制；允许运行目标方法之前进行一些拦截工作，或者在目标方法运行之后进行一些其他处理；</p>
<p>就和JavaWEB中的Filter过滤器很像</p>
<p>通过一个接口：HandlerIntercepter，有三个方法</p>
<ul>
<li><p>preHandle：在目标运行之前调用；返回一个boolean；是否放行</p>
</li>
<li><p>postHandle：在目标运行之后调用：</p>
</li>
<li><p>afterCompletion：在请求整个完成之后；来到目标页面之后</p>
</li>
</ul>
<p>拦截器是一个接口，所以要使用它的实现方法</p>
<p>执行顺序是</p>
<ul>
<li>拦截器的preHandle-目标方法-拦截器postHandle-页面-拦截器的afterCompletion</li>
</ul>
<p>其他流程：</p>
<ul>
<li>只要不放行就不会有后面的流程</li>
<li>已经放行的拦截器的afterCompletion总会执行</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyIntercepter</span> <span class="keyword">implements</span> <span class="title">HandlerInterceptor</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">preHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;pre&quot;</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">postHandle</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;post&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">afterCompletion</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;after&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="SpringMVC的异常处理"><a href="#SpringMVC的异常处理" class="headerlink" title="SpringMVC的异常处理"></a>SpringMVC的异常处理</h2><p>Controller调用service，service调用dao，异常都是向上抛出的，最终有DispatcherServlet找异常处理器进 行异常的处理。</p>
<p>在本类里面写的异常处理可以处理本类里的异常</p>
<h3 id="ExceptionHandler"><a href="#ExceptionHandler" class="headerlink" title="ExceptionHandler"></a>ExceptionHandler</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Controller</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyException</span> </span>&#123;</span><br><span class="line">    <span class="meta">@RequestMapping(&quot;testException&quot;)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">handle01</span><span class="params">()</span></span>&#123;</span><br><span class="line">        System.out.println(<span class="string">&quot;handle01&quot;</span>);</span><br><span class="line">        System.out.println( <span class="number">10</span> / <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;success&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@ExceptionHandler(value = ArithmeticException.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">handle01Execption</span><span class="params">(Exception exception)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;false&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>也可以将异常处理写成全局</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ControllerAdvice</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyException</span> </span>&#123;</span><br><span class="line">    <span class="meta">@ExceptionHandler(value = ArithmeticException.class)</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">handle01Execption</span><span class="params">(Exception exception)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="string">&quot;false&quot;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="ResponseStatus"><a href="#ResponseStatus" class="headerlink" title="ResponseStatus"></a>ResponseStatus</h3><p>自定义异常</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">@ResponseStatus(reason = &quot;找不到&quot;,value = HttpStatus.NOT_FOUND)</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">NotFoundException</span> <span class="keyword">extends</span> <span class="title">RuntimeException</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> serialVersionUID = <span class="number">1L</span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



























































































    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/javaweb%E6%A1%86%E6%9E%B6/" rel="tag"># javaweb框架</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/31/algorithm/backtracking/" rel="prev" title="从八皇后问题到回溯算法">
      <i class="fa fa-chevron-left"></i> 从八皇后问题到回溯算法
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/09/03/java/spring-ioc/" rel="next" title="Spring IOC">
      Spring IOC <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringMVC%E7%9A%84%E5%9F%BA%E6%9C%AC%E6%A6%82%E5%BF%B5"><span class="nav-number">1.</span> <span class="nav-text">SpringMVC的基本概念</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E4%B8%89%E5%B1%82%E6%9E%B6%E6%9E%84%E5%92%8CMVC"><span class="nav-number">1.1.</span> <span class="nav-text">关于三层架构和MVC</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%B8%89%E5%B1%82%E6%9E%B6%E6%9E%84"><span class="nav-number">1.1.1.</span> <span class="nav-text">三层架构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#MVC%E6%A8%A1%E5%9E%8B"><span class="nav-number">1.1.2.</span> <span class="nav-text">MVC模型</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringMVC%E7%9A%84%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B"><span class="nav-number">2.</span> <span class="nav-text">SpringMVC的入门案例</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringMVC%E7%9A%84%E6%A6%82%E8%BF%B0"><span class="nav-number">2.1.</span> <span class="nav-text">SpringMVC的概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringMVC%E7%9A%84%E5%85%A5%E9%97%A8%E7%A8%8B%E5%BA%8F"><span class="nav-number">2.2.</span> <span class="nav-text">SpringMVC的入门程序</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%9B%E5%BB%BAWEB%E5%B7%A5%E7%A8%8B%EF%BC%8C%E5%BC%95%E5%85%A5JAR%E5%8C%85"><span class="nav-number">2.2.1.</span> <span class="nav-text">创建WEB工程，引入JAR包</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E9%85%8D%E7%BD%AE%E6%A0%B8%E5%BF%83%E7%9A%84%E6%8E%A7%E5%88%B6%E5%99%A8-%E9%85%8D%E7%BD%AEDispatcherServlet"><span class="nav-number">2.2.2.</span> <span class="nav-text">配置核心的控制器(配置DispatcherServlet)</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%85%A5%E9%97%A8%E6%A1%88%E4%BE%8B%E7%9A%84%E6%89%A7%E8%A1%8C%E8%BF%87%E7%A8%8B%E5%88%86%E6%9E%90"><span class="nav-number">2.2.3.</span> <span class="nav-text">入门案例的执行过程分析</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E7%9A%84%E7%BB%91%E5%AE%9A"><span class="nav-number">3.</span> <span class="nav-text">请求参数的绑定</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AF%B7%E6%B1%82%E5%8F%82%E6%95%B0%E7%9A%84%E7%BB%91%E5%AE%9A%E8%AF%B4%E6%98%8E"><span class="nav-number">3.1.</span> <span class="nav-text">请求参数的绑定说明</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%B8%B8%E7%94%A8%E7%9A%84%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.</span> <span class="nav-text">常用的注解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#RequestParam%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.1.</span> <span class="nav-text">@RequestParam注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RequestBody%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.2.</span> <span class="nav-text">@RequestBody注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#PathVariable%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.3.</span> <span class="nav-text">@PathVariable注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#RequestHeader%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.4.</span> <span class="nav-text">@RequestHeader注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#CookieValue%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.5.</span> <span class="nav-text">CookieValue注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ModelAttribute%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.6.</span> <span class="nav-text">ModelAttribute注解</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SessionAttributes%E6%B3%A8%E8%A7%A3"><span class="nav-number">4.7.</span> <span class="nav-text">SessionAttributes注解</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Controller%E5%93%8D%E5%BA%94%E6%95%B0%E6%8D%AE%E5%92%8C%E7%BB%93%E6%9E%9C%E8%AF%95%E5%9B%BE"><span class="nav-number">5.</span> <span class="nav-text">Controller响应数据和结果试图</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC%E5%88%86%E7%B1%BB"><span class="nav-number">5.1.</span> <span class="nav-text">返回值分类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">5.1.1.</span> <span class="nav-text">返回字符串</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E8%BF%94%E5%9B%9E%E5%80%BC%E6%98%AFvoid"><span class="nav-number">5.1.2.</span> <span class="nav-text">返回值是void</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#SpringMVC%E6%A1%86%E6%9E%B6%E6%8F%90%E4%BE%9B%E7%9A%84%E8%BD%AC%E5%8F%91%E5%92%8C%E9%87%8D%E5%AE%9A%E5%90%91"><span class="nav-number">5.2.</span> <span class="nav-text">SpringMVC框架提供的转发和重定向</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#forward%E8%AF%B7%E6%B1%82%E8%BD%AC%E5%8F%91"><span class="nav-number">5.2.1.</span> <span class="nav-text">forward请求转发</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#redirect%E9%87%8D%E5%AE%9A%E5%90%91"><span class="nav-number">5.2.2.</span> <span class="nav-text">redirect重定向</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ResponseBody%E5%93%8D%E5%BA%94json%E6%95%B0%E6%8D%AE"><span class="nav-number">5.3.</span> <span class="nav-text">ResponseBody响应json数据</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-RequestBody%E8%8E%B7%E5%8F%96%E8%AF%B7%E6%B1%82%E4%BD%93%E6%95%B0%E6%8D%AE"><span class="nav-number">5.3.1.</span> <span class="nav-text">使用@RequestBody获取请求体数据</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-RequestBody%E6%B3%A8%E8%A7%A3%E6%8A%8Ajson%E7%9A%84%E5%AD%97%E7%AC%A6%E4%B8%B2%E8%BD%AC%E6%8D%A2%E6%88%90JavaBean%E7%9A%84%E5%AF%B9%E8%B1%A1"><span class="nav-number">5.3.2.</span> <span class="nav-text">使用@RequestBody注解把json的字符串转换成JavaBean的对象</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-ResponseBody%E6%B3%A8%E8%A7%A3%E6%8A%8AJavaBean%E5%AF%B9%E8%B1%A1%E8%BD%AC%E6%8D%A2%E6%88%90json%E5%AD%97%E7%AC%A6%E4%B8%B2"><span class="nav-number">5.3.3.</span> <span class="nav-text">使用@ResponseBody注解把JavaBean对象转换成json字符串</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringMVC%E5%AE%9E%E7%8E%B0%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0"><span class="nav-number">6.</span> <span class="nav-text">SpringMVC实现文件上传</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E7%9A%84%E5%9B%9E%E9%A1%BE"><span class="nav-number">6.1.</span> <span class="nav-text">文件上传的回顾</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%96%E5%86%99%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E7%9A%84JSP%E9%A1%B5%E9%9D%A2"><span class="nav-number">6.1.1.</span> <span class="nav-text">编写文件上传的JSP页面</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E7%BC%96%E5%86%99%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0%E7%9A%84Controller%E6%8E%A7%E5%88%B6%E5%99%A8"><span class="nav-number">6.1.2.</span> <span class="nav-text">编写文件上传的Controller控制器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%A4%9A%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0MultipartFile-file-%E9%81%8D%E5%8E%86"><span class="nav-number">6.1.3.</span> <span class="nav-text">多文件上传MultipartFile[] file + 遍历</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringMVC%E7%9A%84%E6%8B%A6%E6%88%AA%E5%99%A8"><span class="nav-number">7.</span> <span class="nav-text">SpringMVC的拦截器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#SpringMVC%E7%9A%84%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86"><span class="nav-number">8.</span> <span class="nav-text">SpringMVC的异常处理</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ExceptionHandler"><span class="nav-number">8.1.</span> <span class="nav-text">ExceptionHandler</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ResponseStatus"><span class="nav-number">8.2.</span> <span class="nav-text">ResponseStatus</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">李寿贤</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">13</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">李寿贤</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://mist.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a>
  </div>

        






<script>
  (function() {
    function leancloudSelector(url) {
      url = encodeURI(url);
      return document.getElementById(url).querySelector('.leancloud-visitors-count');
    }

    function addCount(Counter) {
      var visitors = document.querySelector('.leancloud_visitors');
      var url = decodeURI(visitors.id);
      var title = visitors.dataset.flagTitle;

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url })))
        .then(response => response.json())
        .then(({ results }) => {
          if (results.length > 0) {
            var counter = results[0];
            leancloudSelector(url).innerText = counter.time + 1;
            Counter('put', '/classes/Counter/' + counter.objectId, { time: { '__op': 'Increment', 'amount': 1 } })
              .catch(error => {
                console.error('Failed to save visitor count', error);
              });
          } else {
              Counter('post', '/classes/Counter', { title, url, time: 1 })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    function showTime(Counter) {
      var visitors = document.querySelectorAll('.leancloud_visitors');
      var entries = [...visitors].map(element => {
        return decodeURI(element.id);
      });

      Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({ url: { '$in': entries } })))
        .then(response => response.json())
        .then(({ results }) => {
          for (let url of entries) {
            let target = results.find(item => item.url === url);
            leancloudSelector(url).innerText = target ? target.time : 0;
          }
        })
        .catch(error => {
          console.error('LeanCloud Counter Error', error);
        });
    }

    let { app_id, app_key, server_url } = {"enable":true,"app_id":"xb8ocBOeUvnh1ClRKD6b7Vwm-gzGzoHsz","app_key":"ODH211TGDI1jVYfBVxifNiXt","server_url":null,"security":false};
    function fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${api_server}/1.1${url}`, {
          method,
          headers: {
            'X-LC-Id'     : app_id,
            'X-LC-Key'    : app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      if (CONFIG.page.isPost) {
        if (CONFIG.hostname !== location.hostname) return;
        addCount(Counter);
      } else if (document.querySelectorAll('.post-title-link').length >= 1) {
        showTime(Counter);
      }
    }

    let api_server = app_id.slice(-9) !== '-MdYXbMMI' ? server_url : `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com`;

    if (api_server) {
      fetchData(api_server);
    } else {
      fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
        .then(response => response.json())
        .then(({ api_server }) => {
          fetchData('https://' + api_server);
        });
    }
  })();
</script>


      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/muse.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>















  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : '9AvQGweVbH47hbtztejqnkta-gzGzoHsz',
      appKey     : 'lo0cfhvPh5MqPkgzHzT5n0Az',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
